<script lang="jsx" setup>
import { nextTick, ref } from 'vue';
import dayjs from 'dayjs';
import { PlusOutlined } from '@ant-design/icons-vue';
import useResetTableRef from '@/hooks/common/resetTableRef';
import useSearchData from '@/hooks/common/searchData';
import { deepClone } from '@/utils';
import {
  addProductionFeedDetail,
  addProductionFeedDetail2
} from '@/service/api/modules/work-order-management/production-feed';
import DeliverySchedule from './modules/delivery-schedule.vue';
import EngineeringDocument from './modules/engineering-document.vue';
import Add from './modules/add.vue';

// 获取当天0点和23点29分59秒时间
function getStartTimeAndEndTime() {
  const startTime = dayjs().set('hour', 0).set('minute', 0).set('second', 0).set('millisecond', 0);
  const endTime = dayjs().set('hour', 23).set('minute', 29).set('second', 59).set('millisecond', 999);
  return [startTime, endTime];
}

const commonSearchRef = ref(null);
const [searchParams, resetSearchParams] = useResetTableRef({
  moduleNo: null,
  time: getStartTimeAndEndTime(),
  isFinish: null
});

const stateMap = {
  '-1': '无ICS',
  0: '新录入',
  1: '更改',
  2: '待处理',
  3: '处理中',
  4: '暂停',
  5: '拒审',
  6: '反审核',
  7: '审核中',
  8: '生效',
  9: '完成',
  10: '取消',
  11: '外部ECN',
  12: '外部ECN处理中',
  13: '内部ECN处',
  19: '样板转生产',
  21: '改变',
  22: '待投料',
  23: '已投料',
  25: '失效',
  999: '系统完成',
  1503311132310000: '初审'
};

function formatStatePO(v) {
  return stateMap[v] || '';
}

function formatStatePOColor(v) {
  switch (Number(v)) {
    case 0:
      return '#0080FF';
    case 1:
      return '#E1E100';
    case 2:
      return '#FF8000';
    case 3:
      return '#B15BFF';
    case 4:
      return '#73BF00';
    case 5:
      return '#8E8E8E';
    case 6:
      return '#BEBEBE';
    case 7:
      return '#FF0000';
    case 8:
      return '#BEBEBE';
    case 9:
      return '#0000FF';
    case 10:
      return '#007500';
    case 21:
      return '#FF4500';
    case 25:
      return '#00CED1';
    default:
      return '#0000FF';
  }
}

function formatStatePPC(v) {
  switch (Number(v)) {
    case 0:
      return '新录入';
    case 1:
      return '更改';
    case 2:
      return '待处理';
    case 3:
      return '处理中';
    case 4:
      return '暂停';
    case 5:
      return '回退';
    case 6:
      return '反审核';
    case 7:
      return '审核中';
    case 8:
      return '生效';
    case 9:
      return '完成';
    case 10:
      return '取消';
    case 11:
      return '外部ECN';
    case 12:
      return '外部ECN处理中';
    case 13:
      return '内部ECN处';
    case 21:
      return '改变';
    case 22:
      return '待投料';
    case 23:
      return '已投料';
    default: {
      return '';
    }
  }
}

function formatStatePPCColor(v) {
  switch (Number(v)) {
    case 0:
      return '#0080FF';
    case 1:
      return '#E1E100';
    case 2:
      return '#FF8000';
    case 3:
      return '#B15BFF';
    case 4:
      return '#73BF00';
    case 5:
      return '#8E8E8E';
    case 6:
      return '#BEBEBE';
    case 7:
      return '#FF0000';
    case 8:
      return '#BEBEBE';
    case 9:
      return '#0000FF';
    case 10:
      return '#007500';
    case 21:
      return '#FF4500';
    default:
      return '#0000FF';
  }
}

const formList = [
  {
    type: 'input',
    key: 'moduleNo',
    label: '生产型号',
    span: 6,
    placeholder: '请输入生产型号'
  },
  {
    type: 'dateRangePicker',
    key: 'time',
    label: '时间',
    span: 9,
    showTime: true
  },
  {
    type: 'select',
    key: 'isFinish',
    label: '是否投完',
    placeholder: '请选择是否投完',
    span: 6,
    selectOptions: [
      { label: '是', value: 0 },
      { label: '否', value: 1 }
    ]
  }
];

const topTableRef = ref(null);
const searchData = useSearchData(searchParams);
const topColumn = [
  {
    key: 'dataIndex',
    dataIndex: 'dataIndex',
    title: '序号',
    width: 70,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'ppcState',
    dataIndex: 'ppcState',
    title: '状态',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 70,
    customRender: ({ record }) => {
      return (
        <div style={{ color: formatStatePOColor(record.ppcState) }} class="h-full w-full font-800">
          {formatStatePO(record.ppcState)}
        </div>
      );
    }
  },
  {
    key: 'faState',
    dataIndex: 'faState',
    title: '财务审核状态',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 120,
    customRender: ({ record }) => {
      return (
        <div style={{ color: formatStatePOColor(record.faState) }} class="h-full w-full font-800">
          {formatStatePO(record.faState)}
        </div>
      );
    }
  },
  {
    key: 'prodOrderNo',
    dataIndex: 'prodOrderNo',
    title: '工单号',
    width: 120,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'odrType',
    dataIndex: 'odrType',
    title: '订单类型',
    width: 120,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'liaohao',
    dataIndex: 'liaohao',
    title: '生产型号',
    width: 120,
    align: 'center',
    checked: true,
    ellipsis: true,
    customRender: ({ record }) => {
      return <div class="fonw-800 color-#646cff">{record.liaohao}</div>;
    }
  },
  {
    key: 'odrProdType',
    dataIndex: 'odrProdType',
    title: '加工类型',
    width: 120,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'surfTrea1',
    dataIndex: 'surfTrea1',
    title: '表面处理1',
    width: 190,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'surfTrea2',
    dataIndex: 'surfTrea2',
    title: '表面处理2',
    width: 190,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'qty',
    dataIndex: 'qty',
    title: '工单数量',
    width: 120,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'prodOdrInvQty',
    dataIndex: 'prodOdrInvQty',
    title: '使用库存',
    width: 120,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'issueQty',
    dataIndex: 'issueQty',
    title: '待投数量',
    width: 120,
    align: 'center',
    checked: true,
    ellipsis: true,
    customRender: ({ record }) => {
      return record.qty - record.prodOdrInvQty - record.issPcsQty < 0
        ? 0
        : record.qty - record.prodOdrInvQty - record.issPcsQty;
      // (r.get('qty') - r.get('prodOdrInvQty') - r.get('issPcsQty')) < 0 ? 0 : (r.get('qty') - r.get('prodOdrInvQty') - r.get('issPcsQty'))
    }
  },
  {
    key: 'issPcsQty',
    dataIndex: 'issPcsQty',
    title: '已投料数量',
    width: 120,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'invInQty',
    dataIndex: 'invInQty',
    title: '入库数量',
    width: 120,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'invOutQty',
    dataIndex: 'invOutQty',
    title: '交货数量',
    width: 120,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'invQty',
    dataIndex: 'invQty',
    title: '库存数量',
    width: 120,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'mktDate',
    dataIndex: 'mktDate',
    title: '要求交期',
    width: 160,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'ppcDate',
    dataIndex: 'ppcDate',
    title: '答复交期',
    width: 160,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'planDate',
    dataIndex: 'planDate',
    title: '计划投料日期',
    width: 160,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'prodType',
    dataIndex: 'prodType',
    title: '产品类型',
    width: 120,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'remark',
    dataIndex: 'remark',
    title: '计划备注',
    width: 120,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'remark1',
    dataIndex: 'remark1',
    title: '评审备注',
    width: 120,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'batchType',
    dataIndex: 'batchType',
    title: '批次类型',
    width: 120,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'pedifficulty',
    dataIndex: 'pedifficulty',
    title: '难度系数',
    width: 120,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'custNo',
    dataIndex: 'custNo',
    title: '客户编码',
    width: 120,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'custName',
    dataIndex: 'custName',
    title: '客户名称',
    width: 120,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'custProdNo',
    dataIndex: 'custProdNo',
    title: '客户型号',
    width: 120,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'sellType',
    dataIndex: 'sellType',
    title: '销售方式',
    width: 120,
    align: 'center',
    checked: true,
    ellipsis: true
  },

  {
    key: 'concerned',
    dataIndex: 'concerned',
    title: '安全投产',
    width: 120,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'createBy',
    dataIndex: 'createBy',
    title: '创建者',
    width: 120,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'createDate',
    dataIndex: 'createDate',
    title: '创建日期',
    width: 160,
    align: 'center',
    checked: true,
    ellipsis: true,
    customRender: ({ record }) => {
      dayjs(record.createDate).format('YYYY-MM-DD HH:mm:ss');
    }
  },
  {
    key: 'updateDate',
    dataIndex: 'updateDate',
    title: '最后更改日期',
    width: 160,
    align: 'center',
    checked: true,
    ellipsis: true,
    customRender: ({ record }) => {
      dayjs(record.updateDate).format('YYYY-MM-DD HH:mm:ss');
    }
  }
];

const activeKey = ref('1');

const engineeringDocumentRef = ref(null);
const deliveryScheduleRef = ref(null);

const bottomSearchParams = ref({});
const bottomTableRef = ref(null);
const bottomColumn = [
  {
    key: 'dataIndex',
    dataIndex: 'dataIndex',
    title: '序号',
    width: 70,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'state',
    dataIndex: 'state',
    title: '状态',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 70,
    customRender: ({ record }) => {
      return (
        <div style={{ color: formatStatePPCColor(Number(record.state)) }} class="h-full w-full font-800">
          {formatStatePPC(Number(record.state))}
        </div>
      );
    }
  },
  {
    key: 'issueNo',
    dataIndex: 'issueNo',
    title: '投料单号',
    width: 120,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'moduleNo',
    dataIndex: 'moduleNo',
    title: '生产型号',
    width: 120,
    align: 'center',
    checked: true,
    ellipsis: true,
    customRender: ({ record }) => {
      return <div class="fonw-800 color-#646cff">{record.moduleNo}</div>;
    }
  },
  {
    key: 'custProdNo',
    dataIndex: 'custProdNo',
    title: '客户型号',
    width: 120,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'issueType',
    dataIndex: 'issueType',
    title: '发料类型',
    width: 120,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'workType',
    dataIndex: 'workType',
    title: '工单类型',
    width: 120,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'qty',
    dataIndex: 'qty',
    title: '交货数量(PCS)',
    width: 120,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'sheetQty',
    dataIndex: 'sheetQty',
    title: '大料数量(Sheet)',
    width: 120,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'lotQty',
    dataIndex: 'lotQty',
    title: 'PNL数量',
    width: 120,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'invProvideQty',
    dataIndex: 'invProvideQty',
    title: '使用库存数量(PCS)',
    width: 160,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'issPcsQty',
    dataIndex: 'issPcsQty',
    title: '发料数量(PCS)',
    width: 120,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'scrapRete',
    dataIndex: 'scrapRete',
    title: '预投料率',
    width: 120,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'liveUint',
    dataIndex: 'liveUint',
    title: '有效单元数量(PCS)',
    width: 160,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'invUnit',
    dataIndex: 'invUnit',
    title: '入库数量(PCS)',
    width: 140,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'practicalLength',
    dataIndex: 'practicalLength',
    title: '实开大料长(mm)',
    width: 140,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'practicalWidth',
    dataIndex: 'practicalWidth',
    title: '实开大料宽(mm)',
    width: 140,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'weight',
    dataIndex: 'weight',
    title: '单元重量',
    width: 120,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'pcsarea',
    dataIndex: 'pcsarea',
    title: '单元面积(sq.ft)',
    width: 140,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'remark',
    dataIndex: 'remark',
    title: '备注',
    width: 120,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'createDate',
    dataIndex: 'createDate',
    title: '发料日期',
    width: 120,
    align: 'center',
    checked: true,
    ellipsis: true,
    customRender: ({ record }) => {
      dayjs(record.createDate).format('YYYY-MM-DD HH:mm:ss');
    }
  },
  {
    key: 'createBy',
    dataIndex: 'createBy',
    title: '发料人员',
    width: 120,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'autoCalc',
    dataIndex: 'autoCalc',
    title: '自动计算',
    width: 120,
    align: 'center',
    checked: true,
    ellipsis: true
  }
];

function search() {
  topTableRef.value.getData();
}

function reset() {
  resetSearchParams();
  nextTick(() => {
    search();
  });
}

const currentRow = ref(null);
function handleTableRowClick(row) {
  currentRow.value = deepClone(row);
  bottomSearchParams.value.prodId = row.prodID;
  nextTick(() => {
    bottomTableRef.value.getData();
    engineeringDocumentRef.value.getData({
      prodNo: row.liaohao
    });
  });
}

function handleTableLoadSuccess(data) {
  if (!data.length) return;
  topTableRef.value.setCurrentRowId(data[0]);
  handleTableRowClick(data[0]);
}

const visible = ref(false);
function handleAdd() {
  visible.value = true;
}

const addRef = ref(null);
function addData() {
  console.log('list', addRef.value.saveData());
  const result = addRef.value.saveData();
  if (result) {
    Promise.all([addProductionFeedDetail(result.data), addProductionFeedDetail2(result.list)])
      .then(([r1, r2]) => {
        console.log(r1, r2);
        if (!r1.error && !r2.error) {
          window.$message.success('保存成功');
          search();
        }
      })
      .finally(() => {
        visible.value = false;
      });
  }
}

function handleClose() {
  visible.value = false;
  addRef.value.resetTopModel();
}
</script>

<template>
  <div class="h-full min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <div class="top mb-0.5% h-59.5%">
      <ARow class="h-full" :gutter="16">
        <ACol :span="16" class="h-full min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
          <CommonSearch
            ref="commonSearchRef"
            v-model:searchParams="searchParams"
            :form-list="formList"
            @search="search"
            @reset="reset"
          ></CommonSearch>
          <Table
            ref="topTableRef"
            v-model:searchParams="searchData"
            :column="topColumn"
            :show-row-selection="false"
            auto-generate-uuid
            row-key="screenId"
            :scroll="{ y: 'auto' }"
            is-init-get-data
            url="/mes/BaseVppcissueplanodr/select"
            @table-row-click="handleTableRowClick"
            @table-data-load-sucess="handleTableLoadSuccess"
          >
            <template #title>
              <span class="color-#646cff">生产工单</span>
            </template>
          </Table>
        </ACol>
        <ACol class="h-full" :span="8">
          <ATabs v-model:activeKey="activeKey" type="card" class="my-tabs h-full">
            <ATabPane key="1" force-render>
              <template #tab>
                <span>
                  <span class="iconfont icon-jiaohuojihua"></span>
                  交货计划
                </span>
              </template>
              <DeliverySchedule ref="deliveryScheduleRef" />
            </ATabPane>
            <ATabPane key="2" force-render>
              <template #tab>
                <span>
                  <span class="iconfont icon-gongchengwenjian"></span>
                  工程文件
                </span>
              </template>
              <EngineeringDocument ref="engineeringDocumentRef" />
            </ATabPane>
          </ATabs>
        </ACol>
      </ARow>
    </div>
    <div class="bottom h-40%">
      <Table
        ref="bottomTableRef"
        v-model:searchParams="bottomSearchParams"
        class="h-full"
        :column="bottomColumn"
        :show-row-selection="false"
        auto-generate-uuid
        row-key="screenId"
        :scroll="{ y: 'auto' }"
        :is-init-get-data="false"
        :is-pagination="false"
        url="/mes/BasePpcprodissue/selectBasePpcprodissue"
      >
        <template #title>
          <span class="mr15px color-#646cff">投产明细</span>
          <AButton type="primary" class="mini-btn mr-8px" size="small" ghost :disabled="!currentRow" @click="handleAdd">
            <template #icon>
              <PlusOutlined class="align-sub" />
            </template>
            添加
          </AButton>
        </template>
      </Table>
    </div>

    <Modal
      v-model:visible="visible"
      :destroy-on-close="true"
      :centered="true"
      title="投料输入"
      width="100%"
      height="100vh"
      :modal-warp-style="{ padding: '5px' }"
      @close="handleClose"
    >
      <Add ref="addRef" :row-data="currentRow" />
      <template #footer>
        <div class="modal-footer">
          <AButton @click="handleClose">关闭</AButton>
          <AButton type="primary" @click="addData">保存</AButton>
        </div>
      </template>
    </Modal>
  </div>
</template>

<style lang="scss" scoped>
.top {
  :deep(.ant-tabs) {
    .ant-tabs-nav {
      margin-bottom: 0;
    }

    .ant-tabs-content-holder {
      height: calc(100% - 40px);
      .ant-tabs-content {
        height: 100%;
        .ant-tabs-tabpane {
          height: 100%;
        }
      }
    }
    .ant-tabs-nav-list {
      .ant-tabs-tab {
        border-radius: 6px 6px 0 0;
      }
      .ant-tabs-tab-active {
        background: #646cff;
        .ant-tabs-tab-btn {
          color: #fff;
        }
      }
    }
  }
}
</style>
